﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DMS.Business.Utility;
using DMS.Base;
using DMS.BaseClass;

namespace DMS.Web.Common.ApplicationPages
{
    public partial class UploadFile : System.Web.UI.Page
    {
        #region 事件
        public event EventHandler<FileUploadArgs> FileUploadSucceed;
        public event EventHandler FileUploadFaile;
        #endregion

        #region 成员属性
        private string _AllowFileTypes = string.Empty;

        public string AllowFileTypes
        {
            get { return _AllowFileTypes; }
            set { _AllowFileTypes = value; }
        }

        /// <summary>
        /// 默认（10M）
        /// </summary>
        private long _MaxUploadSize = 10240000;

        /// <summary>
        /// 文件最大上传大小（Byte），默认（10M）
        /// </summary>
        public long MaxUploadSize
        {
            get { return _MaxUploadSize; }
            set { _MaxUploadSize = value; }
        }

        private string _FileID = string.Empty;

        /// <summary>
        /// 覆盖文件的名称（上一次上传返回的文件名，一个GUID），可覆盖上一次上传的文件
        /// </summary>
        public string FileID
        {
            get { return _FileID; }
            set { _FileID = value; }
        }


        private string _Module = string.Empty;
        /// <summary>
        /// 目标存放目录，支持多级存放
        /// </summary>
        public string Module
        {
            get { return _Module; }
            set { _Module = value; }
        }

        public string Remark
        {
            get
            {
                return this.spRemark.InnerHtml;
            }
            set
            {
                this.spRemark.InnerHtml = value;
            }
        }
        public string UploadTitle
        {
            get
            {
                return this.lblUploadTitle.Text;
            }
            set
            {
                this.lblUploadTitle.Text = value;
            }
        }
        #endregion


        #region 界面事件
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Expires = -1;

            this.GetParams();

            string documentName = Request.QueryString["DocuName"];
            string documentLink = Request.QueryString["DocuLink"];
            if (!string.IsNullOrEmpty(documentName) && !string.IsNullOrEmpty(documentLink))
            {
                this.DocuInfo.Attributes["style"] = "display:";
                this.DocuName.InnerText = documentName;
                this.DocuLinnk.HRef = documentLink;
            }
        }

         public static string GetFileName()
        {
            Random rd = new Random();
            StringBuilder serial = new StringBuilder();
            serial.Append(DateTime.Now.ToString("HHmmssff"));
            //serial.Append(rd.Next(0, 1000).ToString());
            return serial.ToString();

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            string msg = string.Empty;
            string ext = VirtualPathUtility.GetExtension(fuSelector.FileName) + ";";

            if (!Page.IsValid || !fuSelector.HasFile)
            {
                msg = "文件验证失败，请联系管理员。";
            }
            else if (!string.IsNullOrEmpty(this.AllowFileTypes)
                     && !this.AllowFileTypes.ToLower().Contains(ext.ToLower()))
            {
                msg = "不允许上传该格式的文件，请重新选择。";
            }
            else if (this.fuSelector.FileContent.Length > this.MaxUploadSize)
            {
                msg = "上传文件大小超过系统限制，请重新选择。";
            }

            if (!string.IsNullOrEmpty(msg))
            {
                ClientHelper.Instance.Alert(msg);
                return;
            }

            try
            {
                //生成将要保存的随机文件名
                string toFilePath = ConfigurationManager.AppSettings["AttachmentsPath"];
                //检查保存的路径 是否有/结尾
                if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";

                //按日期归类保存
                string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
                if (true)
                {
                    toFilePath += datePath;
                }
                string fileName = Path.GetFileName(fuSelector.FileName).Split('.')[0] + "_" + GetFileName() +
                                  Path.GetExtension(fuSelector.FileName);
                //物理完整路径                    
                string toFileFullPath = HttpContext.Current.Server.MapPath(toFilePath);
                //检查是否有该路径  没有就创建
                if (!Directory.Exists(toFileFullPath))
                {
                    Directory.CreateDirectory(toFileFullPath);
                }
                //保存文件
                fuSelector.SaveAs(toFileFullPath + fileName);


//                string fileName = fuSelector.FileName;
//                string filePath = this.GetFilePath(fileName);
//                string fullPath = FileTruck.UploadFile(filePath, fuSelector.FileContent);
                string filePath = toFileFullPath + fileName;
//                string fullPath = "http://thpsb.com/" +filePath;
                if (this.FileUploadSucceed != null)
                {
                    FileUploadArgs arg = new FileUploadArgs();
                    arg.FileName = fileName;
                    arg.FileUrl = filePath;
//                    arg.FullUrl = fullPath;
                    this.FileUploadSucceed(this, arg);
                }

                ClientHelper.Instance.CloseWindow(null, fileName + ";" + filePath.Replace("\\","\\\\"));
            }
            catch (Exception ex)
            {
                if (this.FileUploadFaile != null)
                {
                    this.FileUploadFaile(this, new EventArgs());
                }
                string code = LogHelper.LogException(ex);
                msg = string.Format("上传失败，请联系管理员。\\r\\n错误码：{0}", code);
                ClientHelper.Instance.Alert(msg);
            }
        }
        #endregion

        #region 成员方法
        /// <summary>
        /// 获取参数
        /// </summary>
        private void GetParams()
        {
            if (!string.IsNullOrEmpty(Request["Module"]))
            {
                this._Module = Request["Module"].ToString();
            }

            if (!string.IsNullOrEmpty(Request["FID"]))
            {
                this._FileID = Request["FID"].ToString();
            }

            if (!string.IsNullOrEmpty(Request["MaxSize"]))
            {
                long maxSize = 0;
                if (long.TryParse(Request["MaxSize"].ToString(), out maxSize))
                {
                    this._MaxUploadSize = maxSize;
                }
            }

            if (!string.IsNullOrEmpty(Request["FType"]))
            {
                this._AllowFileTypes = Request["FType"].ToString().ToLower();
            }
        }
        /// <summary>
        /// 生成文件路径
        /// </summary>
        /// <param name="localFileName"></param>
        /// <returns></returns>
        private string GetFilePath(string localFileName)
        {
            string fileName = Guid.NewGuid().ToString();
            if (!string.IsNullOrEmpty(this._FileID)
                && this._FileID.ToUpper() != Guid.Empty.ToString().ToUpper())
            {
                fileName = this._FileID;
            }

            string fileUrl = string.Format("{0}.{1}", fileName, VirtualPathUtility.GetExtension(localFileName).Replace(".", string.Empty));

            return GetTargetFilePath(this._Module, fileUrl);
        }
        public static string GetTargetFilePath(string module, string fileUrl)
        {
            if (string.IsNullOrEmpty(module))
            {
                module = string.Format("TempByDate/{0}", DateTime.Now.ToString("yyyy/MM/dd"));
            }

            return string.Format("{0}/{1}", module, fileUrl);
        }
        #endregion
    }
}